package com.tianbao54.concurrent.look;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.*;

public class AtomicIntegerWithLook {

    private int value ;
    private Lock look = new ReentrantLock();

    public AtomicIntegerWithLook (int value) {
        this.value = value;
    }

    public AtomicIntegerWithLook() {
        this(0);
    }

    public int getValue () {
        try {
            look.tryLock();
            return value;
        } finally {
            look.unlock();
        }
    }

    public void setValue (int value) {
        try {
            look.tryLock();
            this.value = value;
        } finally {
            look.unlock();
        }
    }

    public int getAndSet (int value) {
        try {
            look.tryLock();
            int old = this.value;
            this.value = value;
            return old;
        } finally {
            look.unlock();
        }
    }

    public boolean compareAndSet (int expect , int update) {

        try {
            look.tryLock();
            if (value == expect) {
                this.value = update;
                return true;
            }
            return false;
        } finally {
            look.unlock();
        }
    }

    public int getAndIncrement () {

        try {
            look.tryLock();
            return this.value ++;
        } finally {
            look.unlock();
        }
    }

    public int getAndDecrement () {

        try {
            look.lock();
            return this.value --;
        } finally {
            look.unlock();
        }
    }

    public int incrementAndGet () {

        try {
            look.lock();
            return ++ this.value;
        } finally {
            look.unlock();
        }
    }

    public int decrementAndGet () {

        try {
            look.lock();
            return -- this.value;
        } finally {
            look.unlock();
        }
    }
}
